package thread.threetype.xinhaoliang;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * Semaphore 维护了一个许可集   许可的数量  通过构造函数来指定  在执行操作时候首先获取许可  结束后释放许可
 * acquire 获取一个许可  阻塞的方式获取
 * release 释放一个许可
 *
 * */
public class Test {
    public static void main(String[] args){
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(5);
        for (int index = 0; index < 20; index++) {
            final int NO = index;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println("Accessing:" + NO);
                        Thread.sleep(10000);
                        semaphore.release();
                        System.out.println("------------------" + semaphore.availablePermits());
                    } catch (InterruptedException e) {
                        e.printStackTrace();                }
                }
            };
            executorService.execute(runnable);
        }
        executorService.shutdown();
    }
}
